package com.example.demo.service;

import com.example.demo.common.exception.FailedException;
import com.example.demo.common.result.FailedResult;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.view.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginService {

    private UserMapper userMapper;

    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    public void setTokenService(TokenService tokenService){
        this.tokenService = tokenService;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        this.userMapper = userMapper;
    }


    //更新登录信息

    public void recordLoginInfo(String userId)
    {
        User user = new User();
        user.setId(userId);
    }
    //登录
    public String login(String phone,String password){
            Authentication authentication;
            try {
                //调用UserDetailService
                authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(phone,password));
            }catch (FailedException e){
                throw new FailedException(FailedResult.USERNAME_PASSWORD_ERROR);
            }
            LoginVo loginVo = (LoginVo) authentication.getPrincipal();
            recordLoginInfo(loginVo.getUserID());
            return tokenService.createToken(loginVo);
    }
}
